import {
  ArgumentsHost,
  BadRequestException,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';
import { FastifyReply, FastifyRequest } from 'fastify';
import { CODE } from '../enum/code.enum';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<FastifyReply>();
    const request = ctx.getRequest<FastifyRequest>();
    const status = exception.getStatus();
    let isValidationError = false;
    let errorMessage = '';
    let errorList = [];

    if (
      exception instanceof BadRequestException &&
      (exception as any).response
    ) {
      const message = (exception as any).response.message;
      // 校验BadRequestException的异常信息，判断是否是校验错误
      if (message instanceof Array) {
        // 假设校验错误会包含详细的错误信息数组
        isValidationError = true;
        errorMessage = '字段校验不通过';
        errorList = message;
      }
    }

    response.status(status);
    response.send({
      code: isValidationError ? CODE.VAL_ERROR : CODE.ERROR,
      error: isValidationError ? errorList : exception.message,
      message: isValidationError ? errorMessage : exception.message,
      date: new Date().toLocaleString(),
      path: request.url,
    });
  }
}
